import { AxiosError } from 'axios';
import { useTokenStore } from '@/stores/login/useTokenStore';

class RefreshToken {
  private resolveFns: Function[] = [];
  private loading = false;

  // 写入等待刷新token的请求
  pushResolveFn(resolveFn: Function) {
    this.resolveFns.push(resolveFn);
    this.startRefresh();
  }

  /** 开启刷新 */
  private startRefresh() {
    if (this.loading === false) {
      this.loading = true;
      useTokenStore()
        .refresh()
        .then(() => {
          this.loading = false;
          this.resolveFns.forEach(fn => fn());
          this.resolveFns = [];
        })
        .catch(() => {
          this.loading = false;
          this.resolveFns = [];
          throw new AxiosError('刷新token失败', 'ERR_REFRESH_TOKEN');
        });
    }
  }
}

const refreshToken = new RefreshToken();

export default refreshToken;
